<template>
	<div class="pageWrap bgc">
		<div class="content-warp flex-column-page-wrap">
			<!-- 公用搜索组件 -->
			<LeSearchForm ref="searchForm" v-model:searchData="searchData" :forms="forms" :loading="tableOpts.options.loading"></LeSearchForm>

			<!--  LeTable 组件使用  -->
			<LeTable
				ref="tableRef"
				v-model:searchParams="tableOpts.searchParams"
				v-bind="tableOpts"
				v-model:curRow="tableOpts.curRow"
				v-model:checked-options="checkedColumns"
				:columns="activeColumns"
			>
				<template #toolLeft>
					<el-button type="primary" @click="addHandler">
						<el-icon class="btn-icon">
							<Plus />
						</el-icon>
					</el-button>
					<el-button type="danger" :disabled="curSelectionRows.length === 0" @click="batch_del">
						<el-icon class="btn-icon">
							<Delete />
						</el-icon>
					</el-button>
				</template>

				<template #statusSlot="scope">
					<status-indicator v-if="scope.row.status === 1" pulse type="success"></status-indicator>
					<status-indicator v-else pulse type="danger"></status-indicator>
				</template>

				<template #actionSlot="{ row }">
					<div class="flex flex-align-pack-center">
						<LeIcon class="text-lg text-icon-color cursor-pointer" icon-class="icon-processInfo-mage--edit" @click="table_edit(row)" />

						<LeIcon class="text-lg ml-2 text-rose-700 cursor-pointer" icon-class="icon-processInfo-iconoir--trash" @click="table_del(row)" />
					</div>
				</template>
			</LeTable>
		</div>

		<LeFormConfigDialog
			v-if="visible"
			ref="dialogUserRef"
			v-model="visible"
			:title="`${isCreate ? '新增' : '编辑'}部门`"
			width="600px"
			:form-data="activeData"
			:form-options="formOptions"
			@submit="submitHandler"
		/>
	</div>
</template>
<script lang="tsx" setup>
import department from '@/api/system/department'
import { computed, nextTick, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { useTablePage } from '@/hooks/useTablePage'
import { Plus, Delete } from '@element-plus/icons-vue'
import StatusIndicator from '@/components/StatusIndicator'
import user from '@/api/system/user'

const visible = ref(false) // 弹窗显示隐藏
const isCreate = ref(true)
const activeData = ref({})
const curSelectionRows = ref([]) // 表格选中数据
const formsDialog = ref([
	{
		prop: 'pid',
		label: '上级部门',
		itemType: 'cascader',
		props: {
			value: 'id',
			label: 'name',
			emitPath: false,
			checkStrictly: true
		},
		options: []
	},
	{
		prop: 'name',
		label: '名称',
		itemType: 'input',
		rules: [{ required: true, message: '请输入名称', trigger: 'blur' }]
	},
	{
		prop: 'code',
		label: '编码',
		itemType: 'input',
		rules: [{ required: true, message: '请输入编码', trigger: 'blur' }]
	},
	{
		prop: 'sort',
		label: '排序',
		itemType: 'inputNumber',
		rules: [{ required: true, message: '请输入排序', trigger: 'blur' }]
	},
	{
		prop: 'status',
		label: '状态',
		itemType: 'switch',
		activeText: '正常',
		inactiveText: '禁用'
	},
	{
		prop: 'remark',
		label: '备注',
		itemType: 'input',
		rules: [{ required: true, message: '请输入备注', trigger: 'blur' }]
	},
	{
		prop: 'headId',
		label: '主管',
		itemType: 'select',
		filterable: true,
		options: []
	}
])
// 新增的表单 和 编辑的表单
const formOptions = computed(() => {
	return {
		forms: formsDialog.value,
		labelWidth: 120,
		span: 30,
		showResetBtn: true,
		formConfig: {
			showCancelBtn: true,
			submitLoading: false
		}
	}
})
const groupFilterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const replaceChildren = arr => {
	arr.forEach(item => {
		item.label = item.name
		item.value = item.id
		if (item.children && item.children.length > 0) {
			replaceChildren(item.children)
		}
	})
	return arr
}

// table列表数据请求
const queryList = async () => {
	const { options, searchParams } = tableOpts
	options.loading = true
	try {
		const list = await department.departmentPageApi(searchParams)
		// tableOpts.total = total
		tableOpts.list = list
		formsDialog.value[0].options = list
		// const test = replaceChildren(list)
		// console.log(test);
		// formsDialog.value[1].options = list
	} catch {
		console.log('获取列表数据失败')
		// tableOpts.total = 0
		tableOpts.list = []
		options.loading = false // 更改加载中的 loading值
	} finally {
		options.loading = false
	}
}

const selectionChange = e => {
	// console.error('click 测试', e)
	curSelectionRows.value = e
}

// 表格搜索条件
const forms = ref([
	{
		prop: 'keyword',
		label: '部门名称：',
		itemType: 'input',
		placeholder: '请输入部门名称'
	},
	{
		prop: 'status',
		label: '状态：',
		itemType: 'select',
		placeholder: '请选择状态',
		options: [
			{
				label: '禁用',
				value: 0
			},
			{
				label: '正常',
				value: 1
			}
		]
	}
])

// table 参数
const columns = [
	{
		prop: 'name',
		label: '部门名称',
		minWidth: 250
	},
	{
		prop: 'code',
		label: '编码',
		minWidth: 100
	},
	{
		prop: 'status',
		label: '状态',
		minWidth: 50,
		slots: {
			default: 'statusSlot'
		}
	},
	{
		prop: 'remark',
		label: '备注',
		minWidth: 100
	},
	{
		prop: 'sort',
		label: '排序',
		minWidth: 80
	},
	{
		prop: 'updateBy',
		label: '修改人',
		minWidth: 100
	},
	{
		prop: 'updateTime',
		label: '修改时间',
		minWidth: 150
	},
	{
		prop: 'createBy',
		label: '创建人',
		minWidth: 100
	},
	{
		prop: 'createTime',
		label: '创建时间',
		minWidth: 150
	},
	{
		prop: 'action',
		label: '操作',
		width: 100,
		align: 'center',
		fixed: 'right',
		slots: {
			default: 'actionSlot'
		}
	}
]

const { searchData, tableOpts, checkedColumns, activeColumns, updateParams } = useTablePage(
	{
		options: {
			showIndex: false,
			defaultExpandAll: false,
			onSelectionChange: selectionChange
		},
		// 需要展示的列
		columns,
		// 控制列配置
		columnsConfig: {
			columns
		}
	},
	{
		queryList,
		fetchImmediate: false
	}
)

// 删除
const deleteItem = async ids => {
	// try {
	await department.departmentDeleteApi(ids)
	ElMessage.success(`删除成功~`)
	updateParams()
	// } catch (e) {
	// 	console.log('删除失败')
	// 	ElMessage.error(`删除失败~`)
	// }
}

// 单个删除
const table_del = (row: any) => {
	ElMessageBox.confirm(`确认删除「${row.name}」这条数据？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'error'
	}).then(async () => {
		deleteItem([row.id])
	})
}

//批量删除
const batch_del = () => {
	const ids = curSelectionRows.value.map(item => item.id) // 多选数据
	ElMessageBox.confirm('是否删除选中数据？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'error',
		buttonSize: 'default'
	}).then(() => {
		deleteItem(ids)
	})
}

const table_edit = async row => {
	isCreate.value = false
	activeData.value = { ...row, status: row.status ? true : false }
	visible.value = true
}

// 弹窗事件
const submitHandler = async params => {
	formOptions.value.formConfig.submitLoading = true
	try {
		params.status = params.status ? 1 : 0
		params.id = activeData.value.id ? activeData.value.id : null
		params.headName = formOptions.value.forms[6].options.find(item => item.value === params.headId).label
		await department.departmentAddOrEditSaveApi(params)
		ElMessage.success(`${isCreate.value ? '新增' : '修改'}成功~`)
		visible.value = false
		updateParams()
		formOptions.value.formConfig.submitLoading = false
	} catch (e) {
		console.log(e)
		formOptions.value.formConfig.submitLoading = false
	}
}

// 获取全部的人员信息
const getUserList = async () => {
	try {
		var { records } = await user.userPageApi({
			page: 1,
			pageSize: 9999
		})
		formOptions.value.forms[6].options = records.map(item => {
			return { value: item.id, label: item.realName }
		})
	} catch (e) {
		console.log(e)
	}
}

const addHandler = () => {
	isCreate.value = true
	activeData.value = {}
	visible.value = true
}
nextTick(() => {
	queryList()
	getUserList()
})

watch(groupFilterText, val => {
	treeRef.value!.filter(val)
})
</script>
